<template lang="pug">
mt-dialog(
  v-model="appmodel"
  cancel-text="取消"
  title="组合项目"
  :on-close="updateModel"
  hide-confirm
  :on-cancel="updateModel"
  width="800"
)
  el-tabs(v-model="activeName" @tab-change="query('tableData')")
    el-tab-pane(name="添加项目",label="添加项目")
      data-page(
          v-bind="pageParams"
      )
      mt-table(
        v-bind="tableProps"
      )
    el-tab-pane(name="删除项目",label="删除项目")
      data-page(
            v-bind="pageParams"
      )
      mt-table(
        v-bind="tableProps"
      )
</template>

<script setup lang="ts">
import type { PortfolioProjectEntity } from "@scmt/api-lis-portfolio-project";
import { type QueryPagination, useApi } from "@scmt/core-api";
import { useQuery } from "@scmt/common-hooks";
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type TableProps,
  useNotify,
} from "@scmt/common-components";
import type { MedicalAdviceQueryParams } from "@scmt/api-bdm-medical-advice";
//添加 Props属性
const props = defineProps({
  selectEquipment: Object,
  instrumentId: String,
});
const $api = useApi();
const $notify = useNotify();

const activeName = ref<null | String>("添加项目");
const appliList = ref<Array<PortfolioProjectEntity>>([]);
const projectId = computed(() => props.selectEquipment?.id);
const instrument = computed(() => props.instrumentId);
const appmodel = defineModel({
  default: false,
});
const emit = defineEmits(["message-to-parent"]);
const queryPramas = reactive<MedicalAdviceQueryParams>({
  instrumentId: instrument,
  specimenId: projectId,
  pageNum: 1,
  pageSize: 20,
});
const updateModel = () => {
  appmodel.value = false;
};

const { query, data, loadingMap } = useQuery({
  tableData: (q: any) => {
    const params = Object.assign({}, queryPramas, q);
    if (activeName.value == "添加项目") {
      return $api.lis.portfolioProject.getNotRelatedSpecimenProjectPageList(
        params
      );
    } else if (activeName.value == "删除项目") {
      return $api.lis.portfolioProject.getRelatedSpecimenProjectPageList(
        params
      );
    }
  },
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "name",
      label: "组合项目",
    },
  ];

  const headerActions: Action[] =
    activeName.value == "添加项目"
      ? [{ event: "add", label: "批量添加" }]
      : [{ event: "destroy", label: "批量删除" }];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => query("tableData"),
    onAct: onPageActions,
    columns: 2,
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "selection",
        label: "序号",
        width: "60px",
      },
      {
        prop: "name",
        label: "组合项目名称",
        width: 150,
      },
      {
        prop: "code",
        label: "组合项目编码",
      },
      {
        prop: "tubeName",
        label: "试管名称",
      },
      {
        label: "操作",
        actions:
          activeName.value == "添加项目"
            ? [{ event: "add", label: "添加" }]
            : [{ event: "destroy", label: "删除" }],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) => query("tableData", pagination),
    onSelectionChange: (data) => {
      appliList.value = [];
      appliList.value = data;
    },
  };
  return tableProps;
});
const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
      if (!model && appliList.value.length < 1) {
        $notify.error("请选择需要添加的申请项目");
        return;
      }
      if (appliList.value.length > 0) {
        if (!isAllEqual(appliList.value)) {
          $notify.error("所选申请项目不是同一合管规则");
          return;
        }
      }
      const projectIdData = [].concat(model ?? appliList.value).map((item) => {
        return item.id;
      });
      const projectNameData = []
        .concat(model ?? appliList.value)
        .map((item) => {
          return item.name;
        });
      $api.lis.specimen.porject
        .addProject(projectId.value ?? "", projectIdData)
        .then(() => {
          $notify.success("添加项目成功");
          emit("message-to-parent", projectNameData, "add");
          query("tableData");
        })
        .catch((error) => {
          $notify.error(error.message);
        });
      break;
    case "destroy":
      if (!model && appliList.value.length < 1) {
        $notify.error("请选择需要添加的申请项目");
        return;
      }
      const projectIdList = [].concat(model ?? appliList.value).map((item) => {
        return item.id;
      });
      const projectNameList = []
        .concat(model ?? appliList.value)
        .map((item) => {
          return item.name;
        });
      $api.lis.specimen.porject
        .deleteProject(projectId.value ?? "", projectIdList)
        .then(() => {
          $notify.success("删除项目成功");
          emit("message-to-parent", projectNameList, "delete");
          query("tableData");
        })
        .catch((error) => {
          $notify.error(error.message);
        });
      break;
  }
};

const isAllEqual = (array: Array<PortfolioProjectEntity>) => {
  const uniqueIds = new Set(array.map((i) => i.combinedId));
  return uniqueIds.size === 1;
};

watch(
  appmodel,
  (visible: boolean) => {
    if (visible) {
      activeName.value = "添加项目";
      queryPramas.name = "";
      query("tableData", {
        projectId: projectId.value,
        instrumentId: instrument.value,
      });
    }
  },
  {
    immediate: true,
  }
);
</script>
